package com.yxq.mdt.app.modules.search.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.TimeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.glide.GlideHelper;
import com.yxq.mdt.app.modules.personal.adapter.DynamicImagesListAdapter;
import com.yxq.mdt.app.modules.personal.bean.PublishBean;
import com.yxq.mdt.app.modules.picturebrowse.ui.PictureActivity;
import com.yxq.mdt.app.modules.search.bean.SearchGroupBean;
import com.yxq.mdt.app.modules.search.bean.SearchTopicBean;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.CircleTopicAc;
import com.yxq.mdt.app.utils.GridSpacingItemDecoration;
import com.yxq.mdt.app.utils.MediaPlayerHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;

/**
 * @author L
 * @time 2019-10-21
 * @describe 搜索-内容列表
 */
public class SearchTopicListAdapter extends BaseQuickAdapter<SearchTopicBean.ListBean, BaseViewHolder> {
    private String content = "";
    private String contentTv = "";
    SpannableStringBuilder spannableStringBuilder;
    public CountDownTimer countDownTimer;

    public SearchTopicListAdapter(int layoutResId, @Nullable List<SearchTopicBean.ListBean> data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, SearchTopicBean.ListBean item) {
        int len = 0;
        int audioLen = 0;
        ImageView avatar = helper.getView(R.id.item_layout_nike_img);
        RecyclerView recyclerView = helper.getView(R.id.item_layout_content_recyclerView);
        JzvdStd jzvdStd = helper.getView(R.id.item_social_video_player);
        LinearLayout lint = helper.getView(R.id.item_social_lint);
        TextView textView = helper.getView(R.id.item_tv_subject);
        LinearLayout voice = helper.getView(R.id.publish_save_voice);
        ImageView voiceNote = helper.getView(R.id.publish_note);
        TextView voiceTime = helper.getView(R.id.publish_add_voice_time);
        contentTv = item.getContent();

        contentTv = item.getContent();
        if (item.getContent() != null) {
            if (item.getContent().contains("#")) {
                content = (item.getContent().substring(item.getContent().indexOf("#"), item.getContent().lastIndexOf("#") + 1));
            } else {
                content = item.getContent();
            }
            spannableStringBuilder = new SpannableStringBuilder("");

            if (!TextUtils.isEmpty(contentTv)) {
                spannableStringBuilder.append(contentTv);
            }
            if (item.getContent().contains("#")) {
                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#ffa800"));
                spannableStringBuilder.setSpan(foregroundColorSpan, 0, (item.getContent().substring(item.getContent().indexOf("#"), item.getContent().lastIndexOf("#") + 1)).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.parseColor("#222222")), (item.getContent().substring(item.getContent().indexOf("#"), item.getContent().lastIndexOf("#") + 1)).length(), spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                ClickableSpan clickableSpan = new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View view) {
                        Intent it = new Intent(mContext, CircleTopicAc.class);
                        it.putExtra("topicId", item.getId());
                        it.putExtra("topic", (item.getContent().substring(item.getContent().indexOf("#"), item.getContent().lastIndexOf("#") + 1)));
                        mContext.startActivity(it);
                    }
                };
                //文本可点击，有点击事件
                spannableStringBuilder.setSpan(clickableSpan, 0, content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //设置此方法后，点击事件才能生效
                textView.setMovementMethod(LinkMovementMethod.getInstance());
                textView.setText(spannableStringBuilder);
            } else {
                helper.setText(R.id.item_tv_subject, item.getContent());
                helper.setTextColor(R.id.item_tv_subject, Color.parseColor("#222222"));
                textView.setTextColor(Color.parseColor("#222222"));
            }

        }
        if (item.getGroupName() != null) {
            helper.setText(R.id.group_name, item.getGroupName());
            GlideHelper.setLoadRoundImage(mContext, item.getGroupLogo(), R.color.gray, helper.getView(R.id.item_iv_group));
            helper.setGone(R.id.group_lint, true);
            helper.setGone(R.id.group_lint, true);
        } else {
            helper.setGone(R.id.group_lint, false);
        }
        helper.addOnClickListener(R.id.group_lint);
        //昵称
        helper.setText(R.id.item_layout_nike_name, item.getGsName());
        //头像
        GlideHelper.setLoadRoundImage(mContext, item.getHeadimg(), R.mipmap.head_icon, avatar);
        //浏览数
        helper.setText(R.id.item_tv_count_browse, item.getViewCount() + "次浏览");
        //点赞数
        helper.setText(R.id.item_layout_content_browse, item.getUpCount() + "");
        //评论数
        helper.setText(R.id.item_layout_content_give_like, item.getCommentCount() + "");
        //发布时间
        helper.setText(R.id.item_layout_time, TimeUtils.getFriendlyTimeSpanByNow(item.getCreateDate(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
        //性别
        helper.setImageResource(R.id.item_iv_sex, item.getSex() == 1 ? R.mipmap.xb_nan : R.mipmap.xb_nv);

        //1 图片 2 视频
        if (item.getFileList() != null && item.getFileList().size() > 0 && "1".equals(item.getFileList().get(0).getClass1())) {
            recyclerView.setVisibility(View.VISIBLE);
            lint.setVisibility(View.GONE);
            voice.setVisibility(View.GONE);
            DynamicImagesListAdapter dynamicImagesListAdapter = new DynamicImagesListAdapter(R.layout.item_layout_social_list, item.getFileList());
            recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
            recyclerView.setAdapter(dynamicImagesListAdapter);
            recyclerView.addItemDecoration(new GridSpacingItemDecoration(3, 1, false));
            dynamicImagesListAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    Intent intent = new Intent(mContext, PictureActivity.class);
                    intent.putExtra("position", position);
                    ArrayList<String> images = new ArrayList<>();
                    for (PublishBean.ListBean.FileListBean fileListBean : item.getFileList()) {
                        images.add(fileListBean.getFile());
                    }
                    intent.putExtra("images", images);
                    mContext.startActivity(intent);
                }
            });
        } else if (item.getFileList() != null && item.getFileList().size() > 0 && "2".equals(item.getFileList().get(0).getClass1())) {
            ImageView imageViewVideo = jzvdStd.thumbImageView;
            imageViewVideo.setScaleType(ImageView.ScaleType.CENTER_CROP);
            GlideHelper.setLoadImage(mContext, item.getFileList().get(0).getFile(), R.color.gray, imageViewVideo);
            jzvdStd.setUp(item.getFileList().get(0).getFile(), "", Jzvd.SCREEN_NORMAL);
            Jzvd.setVideoImageDisplayType(JzvdStd.VIDEO_IMAGE_DISPLAY_TYPE_FILL_SCROP);
            lint.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            voice.setVisibility(View.GONE);
        } else if (item.getFileList() != null && item.getFileList().size() > 0 && "6".equals(item.getFileList().get(0).getClass1())) {
            recyclerView.setVisibility(View.GONE);
            lint.setVisibility(View.GONE);
            voice.setVisibility(View.VISIBLE);
            if (item.getFileList() != null && item.getFileList().size() > 0 && item.getFileList().get(0).getClass2() != 0) {
                audioLen = item.getFileList().get(0).getClass2();
                if (audioLen < 1000) {
                    voiceTime.setText(audioLen + "″");
                } else {
                    audioLen = audioLen / 1000;
                    voiceTime.setText(audioLen + "″");
                }
            }
            int finalAudioLen = audioLen;
            voice.setOnClickListener(view -> {
                MediaPlayerHelper.playSound(item.getFileList().get(0).getFile());
                getTime(finalAudioLen + "", voiceNote, voiceTime);
                countDownTimer.start();
            });
        } else {
            //文字
            recyclerView.setVisibility(View.GONE);
            lint.setVisibility(View.GONE);
            voice.setVisibility(View.GONE);
        }
    }

    /**
     * @param playTime  开始时间
     * @param imageView 获取当前控件
     * @param timeTv    获取显示秒数
     */
    private void getTime(String playTime, ImageView imageView, TextView timeTv) {
        imageView.setImageResource(R.mipmap.voice_note_new);
        countDownTimer = new CountDownTimer(Integer.parseInt(playTime) * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeTv.setText(millisUntilFinished / 1000 + "″");
            }

            @Override
            public void onFinish() {
                timeTv.setText(playTime + "″");
                imageView.setImageResource(R.mipmap.voice_note);
                countDownTimer.cancel();
            }
        };
    }

}
